<?php

class Form
{
	protected $fields = array();
	
	public function __construct($fields = array())
	{
		foreach ($fields as $field) {
			if (!$field instanceof FormField) {
				$field = new FormField($field);
			}
			$this->fields[$field->name] = $field;
		}
	}
	
	/**
	 * Automatically load settings from template.
	 *
	 * @param string $template HTML fragment containing form
	 * @param string $id HTML id of the template
	 */
	static public function fromTemplate($template, $id = null)
	{
		// TODO: Implement
	}
	
	public function checkAnswer()
	{
		$result = array();
		
		foreach ($this->fields as $field) {
			var_dump($field);
			if (($result[$field->name] = $field->result()) === null) {
				// If one field fails, all fields fail
				return false;
			}
		}
		
		return $result;
	}
	
	public function __get($key)
	{
		return $this->fields[$key];
	}
}

class FormField
{
	public $name;
	protected $form;
	
	public function __construct($form, $field) {
		$this->form = $form;
		
		if (is_string($field)) {
			// See if field name is associated with a template
			$this->applyTemplate($field);
			
			// Use string as field name
			$this->name = $field;
		} elseif (is_array($field)) {
			$this->applySettings($field);
		} else {
			die('Invalid form field name.');
		}
	}
	
	public function result() {
		return isset($_REQUEST[$this->name]) ? $_REQUEST[$this->name] : null;
	}
	
	public function applyTemplate($name) {
		switch ($name) {
			case 'email':
				$this->validator = new EmailValidator();
				break;
			case 'password':
				$this->type = 'password';
				break;
			case 'password_repeat':
				$this->type = 'password';
				$this->validator = new EqualityValidator('password');
				break;
		}
	}
	
	public function applySettings($s) {
		
	}
}
?>